<template>
    <van-nav-bar
            title="购物车"
            left-arrow
            fixed
            @click-left="$router.go(-1)"
    ></van-nav-bar>

    <van-empty v-if="cartIsEmpty" description="购物车还没有商品哦~"/>
    <div v-else class="cart-list">
        <CartItem v-for="item in cartList" :item="item" :key="item.id"></CartItem>
    </div>

    <van-submit-bar :price="totalAmount * 100" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="cartAllChecked" checked-color="#ee0a24">全选</van-checkbox>
    </van-submit-bar>
    <FooterLayout></FooterLayout>
</template>

<script setup>
  import { computed } from 'vue'
  import { getCartList } from '@/api/cart.js'
  import { useStore } from 'vuex'
  import { useRouter } from 'vue-router'
  import CartItem from './components/CartItem.vue'
  import FooterLayout from '@/components/FooterLayout.vue'
  import { Toast } from 'vant'

  const store = useStore()
  const router = useRouter()

  const cartList = computed(() => {
    return store.state.cartList
  })
  const cartIsEmpty = computed(() => cartList.value.length === 0)

  const loadCartList = async () => {
    const { status, data } = await getCartList()
    if (status === 200) {
      data.valid.forEach(item => item.checked = true)
      store.commit('setCartList', data.valid)
      // store.commit('clearCartList')
      // await nextTick()
      // data.valid.forEach(item => store.commit('addCart', item))
    }
  }
  loadCartList()

  const cartAllChecked = computed({
    get() {
      return !cartList.value.find(item => !item.checked)
    },
    set(checked) {
      store.commit('cartAllCheckedChange', { checked })
    }
  })

  const totalAmount = computed(() => {
    return !cartList.value ? 0 : cartList.value.filter(item => item.checked).reduce((sum, item) => {
      sum += item.truePrice * item.cart_num
      return sum
    }, 0)
  })

  const onSubmit = () => {
    const cartIds = cartList.value.filter(cart => cart.checked).map(cart => cart.id).join(",")
    console.log(cartIds)
    if (!cartIds) {
      Toast.fail('请选择商品')
      return
    }
    router.push({
      name: 'order-confirm',
      params: {
        cartIds,
      }
    })
  }
</script>

<style lang="scss" scoped>

    .van-submit-bar {
        margin-bottom: 50px;
    }

    .cart-list {
        margin-top: 50px;
        margin-bottom: 100px;
    }
</style>
